package com.ponhu.ea2.goodsCenter.provider.facade.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ponhu.ea2.constants.CommonConstant;
import com.ponhu.ea2.dto.CloudTradeGoodsDto;
import com.ponhu.ea2.dto.CloudTradeGoodsV2Dto;
import com.ponhu.ea2.dto.DictItemDataDto;
import com.ponhu.ea2.entity.CloudTradeGoods;
import com.ponhu.ea2.goodsCenter.provider.service.CloudTradeGoodsService;
import com.ponhu.ea2.goodsCenter.provider.service.PhSysDictItemService;
import com.ponhu.ea2.service.facade.CloudTradeService;
import com.ponhu.ea2.support.exception.BusinessRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.ponhu.ea2.enums.ResponseCodeEnum.*;

/**
 * 对接云商接口
 *
 * @author Wang
 * @date 2021/10/20 4:51 下午
 */
@Slf4j
@DubboService(version = "1.0.0", interfaceClass = CloudTradeService.class, timeout = 6000)
public class CloudTradeServiceImpl implements CloudTradeService {

    @Autowired
    private PhSysDictItemService sysDictItemService;
    @Autowired
    private CloudTradeGoodsService cloudTradeGoodsService;

    @Override
    public boolean addOrUpdateDictItem(List<DictItemDataDto> dictItemDataList) {
        return sysDictItemService.addOrUpdateDictItem(dictItemDataList);
    }

    /**
     * 添加云商商品
     *
     * @param cloudTradeGoodsDto
     * @return
     */
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addCloudTradeGoods(CloudTradeGoodsDto cloudTradeGoodsDto) {
        CloudTradeGoods goods = cloudTradeGoodsService.getCloudTradeGoodsByChannelGoodsCode(cloudTradeGoodsDto.getChannelGoodsCode());
        if (goods != null) {
            log.error("商品中心-添加云商商品信息失败, 该渠道商品编码已存在：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_CHANNEL_CODE_IS_EXISTS_800104);
        }

        CloudTradeGoods cloudTradeGoods = new CloudTradeGoods();

        //设置属性信息
        setCloudTradeGoodsValue(cloudTradeGoodsDto, cloudTradeGoods);

        boolean res = cloudTradeGoodsService.addCloudTradeGoods(cloudTradeGoods);
        if (res) {
            log.info("商品中心-添加云商商品信息成功：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            return true;
        } else {
            log.error("商品中心-添加云商商品信息失败，保存数据库失败：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_SAVE_DB_EXCEPTION_800105);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addCloudTradeGoodsV2(CloudTradeGoodsV2Dto cloudTradeGoodsDto) {
        CloudTradeGoods goods = cloudTradeGoodsService.getCloudTradeGoodsByChannelGoodsCode(cloudTradeGoodsDto.getChannelGoodsCode());
        if (goods != null) {
            log.error("商品中心-添加云商商品信息失败, 该渠道商品编码已存在：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_CHANNEL_CODE_IS_EXISTS_800104);
        }

        CloudTradeGoods cloudTradeGoods = new CloudTradeGoods();

        //设置属性信息
        setCloudTradeGoodsValueV2(cloudTradeGoodsDto, cloudTradeGoods);

        cloudTradeGoods.setGoodsName(cloudTradeGoods.getGoodsName() == null ? null: cloudTradeGoods.getGoodsName().trim());

        boolean res = cloudTradeGoodsService.addCloudTradeGoods(cloudTradeGoods);
        if (res) {
            log.info("商品中心-添加云商商品信息成功：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            return true;
        } else {
            log.error("商品中心-添加云商商品信息失败，保存数据库失败：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_SAVE_DB_EXCEPTION_800105);
        }
    }

    /**
     * 批量添加云商商品
     *
     * @param cloudTradeGoodsDtoList
     * @return
     */
    @Override
    public boolean addCloudTradeGoodsList(List<CloudTradeGoodsDto> cloudTradeGoodsDtoList) {
        for (CloudTradeGoodsDto cloudTradeGoodsDto : cloudTradeGoodsDtoList) {
            if (!addCloudTradeGoods(cloudTradeGoodsDto))
                return false;
        }
        return true;
    }

    @Override
    public boolean addCloudTradeGoodsListV2(List<CloudTradeGoodsV2Dto> cloudTradeGoodsDtoList) {
        for (CloudTradeGoodsV2Dto cloudTradeGoodsDto : cloudTradeGoodsDtoList) {
            if (!addCloudTradeGoodsV2(cloudTradeGoodsDto))
                return false;
        }
        return true;
    }

    private void setCloudTradeGoodsValueV2(CloudTradeGoodsV2Dto cloudTradeGoodsDto, CloudTradeGoods cloudTradeGoods) {
        BeanUtils.copyProperties(cloudTradeGoodsDto, cloudTradeGoods);

        //添加附件
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getAnnexList())) {
            cloudTradeGoods.setAnnex(String.join(",", cloudTradeGoodsDto.getAnnexList()));
        }

        //添加配件
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getAccessoryList())) {
            cloudTradeGoods.setAccessory(String.join(",", cloudTradeGoodsDto.getAccessoryList()));
        }

        //添加属性
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getPropertyList())) {
            cloudTradeGoods.setProperties(JSONObject.toJSONString(cloudTradeGoodsDto.getPropertyList()));
        }

        //添加图片
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getDetailImages())) {
            //进行图片域名转换
            cloudTradeGoods.setDetailImage(convertCloudTradeImgDomain(cloudTradeGoodsDto.getDetailImages()));
        }
        if(StringUtils.isNotBlank(cloudTradeGoods.getMainImage())){
            cloudTradeGoods.setMainImage(convertCloudTradeImgDomain(cloudTradeGoodsDto.getMainImage()));
        }
    }

    @Deprecated
    private void setCloudTradeGoodsValue(CloudTradeGoodsDto cloudTradeGoodsDto, CloudTradeGoods cloudTradeGoods) {
        BeanUtils.copyProperties(cloudTradeGoodsDto, cloudTradeGoods);

        //添加附件
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getAnnexList())) {
            cloudTradeGoods.setAnnex(JSONArray.toJSONString(cloudTradeGoodsDto.getAnnexList()));
        }

        //添加配件
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getAccessoryList())) {
            cloudTradeGoods.setAccessory(JSONArray.toJSONString(cloudTradeGoodsDto.getAccessoryList()));
        }

        //添加属性
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getPropertyList())) {
            cloudTradeGoods.setProperties(JSONObject.toJSONString(cloudTradeGoodsDto.getPropertyList()));
        }

        //添加图片
        if (CollectionUtils.isNotEmpty(cloudTradeGoodsDto.getDetailImages())) {
            cloudTradeGoods.setDetailImage(String.join("|", cloudTradeGoodsDto.getDetailImages()));
        }
    }

    /**
     * 更新云商商品
     *
     * @param cloudTradeGoodsDto
     */
    @Deprecated
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCloudTradeGoods(CloudTradeGoodsDto cloudTradeGoodsDto) {
        //查询商品
        CloudTradeGoods goods = cloudTradeGoodsService.getCloudTradeGoodsByChannelGoodsCode(cloudTradeGoodsDto.getChannelGoodsCode());

        if (goods == null) {
            log.error("商品中心-更新云商商品信息失败,商品不存在：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_NOT_EXISTS_800100);
        }
        if (CommonConstant.CLOUD_TRADE_GOODS_STATUS.PASS == goods.getStatus()) {
            log.error("商品中心-更新云商商品信息失败,商品已通过审核：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_CHECKED_PASS_CAN_NOT_UPDATE_800106);
        }

        CloudTradeGoods cloudTradeGoods = new CloudTradeGoods();
        //设置属性值
        setCloudTradeGoodsValue(cloudTradeGoodsDto, cloudTradeGoods);
        if (CommonConstant.CLOUD_TRADE_GOODS_STATUS.NO_PASS == goods.getStatus()) {
            cloudTradeGoods.setStatus(CommonConstant.CLOUD_TRADE_GOODS_STATUS.NO_CHECK);
        }

        boolean res = cloudTradeGoodsService.updateCloudTradeGoods(cloudTradeGoods);
        if (res) {
            log.info("商品中心-更新云商商品信息成功：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            return true;
        } else {
            log.error("商品中心-更新云商商品信息失败，保存数据库失败：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_UPDATE_DB_EXCEPTION_800107);
        }
    }

    /**
     * 更新云商商品
     * @param cloudTradeGoodsDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateCloudTradeGoodsV2(CloudTradeGoodsV2Dto cloudTradeGoodsDto) {
        //查询商品
        CloudTradeGoods goods = cloudTradeGoodsService.getCloudTradeGoodsByChannelGoodsCode(cloudTradeGoodsDto.getChannelGoodsCode());

        if (goods == null) {
            log.error("商品中心-更新云商商品信息失败,商品不存在：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_NOT_EXISTS_800100);
        }

        CloudTradeGoods cloudTradeGoods = new CloudTradeGoods();
        //设置属性值
        setCloudTradeGoodsValueV2(cloudTradeGoodsDto, cloudTradeGoods);

        cloudTradeGoods.setGoodsName(cloudTradeGoods.getGoodsName() == null ? null: cloudTradeGoods.getGoodsName().trim());

        //审核通过与未通过状态，修改成待审核状态
        if (CommonConstant.CLOUD_TRADE_GOODS_STATUS.NO_PASS == goods.getStatus() ||
                CommonConstant.CLOUD_TRADE_GOODS_STATUS.PASS == goods.getStatus()) {
            cloudTradeGoods.setStatus(CommonConstant.CLOUD_TRADE_GOODS_STATUS.NO_CHECK);
        }

        boolean res = cloudTradeGoodsService.updateCloudTradeGoods(cloudTradeGoods);

        if (res) {
            log.info("商品中心-更新云商商品信息成功：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            return true;
        } else {
            log.error("商品中心-更新云商商品信息失败，保存数据库失败：{}", JSONObject.toJSONString(cloudTradeGoodsDto));
            throw new BusinessRuntimeException(CLOUD_TRADE_GOODS_UPDATE_DB_EXCEPTION_800107);
        }
    }
}
